//
//  SLWebViewController.m
//  shunlianPower2
//
//  Created by 陈镇 on 2018/1/4.
//  Copyright © 2018年 顺联网络. All rights reserved.
//

#import "SLWebViewController.h"

//#import "LHNetworkArgument.h"
@interface SLWebViewController ()
/// 用来标记视图是否已经出现
@property (nonatomic, assign) BOOL viewDidAppeared;
/** qmuibu */
@property (nonatomic, strong) UIBarButtonItem *refreshBtn;

@property (nonatomic, strong) WKWebViewConfiguration *configuration;

@end

@implementation SLWebViewController



- (instancetype)initWithUrl:(NSString *)aUrl {
    if (self = [super init]) {
        self.url = aUrl;
    }
    return self;
}

- (instancetype)initWithHTMLString:(NSString *)htmlString {
    if (self = [super init]) {
        self.htmlString = htmlString;
        
    }
    return self;
}


- (void)loadView {
    [super loadView];
    [self requestHTML];
}

- (void)dealloc {
    [self clearData];
}

#pragma mark - Methods

- (void)requestHTML {
    if (self.webView) {
        [self.webView removeFromSuperview];
        [self clearData];
    }
    _configuration = [[WKWebViewConfiguration alloc] init];

   
    self.webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, NavigationContentTop, SCREEN_WIDTH, SCREEN_HEIGHT - NavigationContentTop) configuration:_configuration];
    self.webView.scrollView.bounces = NO;
    self.webView.scrollView.showsVerticalScrollIndicator = NO;

    
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
    self.webView.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal;
    [self.view addSubview:self.webView];
    [self addProgressBarForWebView];
    if (self.url) {
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self cz_URLWithString:self.url]];
        if ([self.url hasPrefix:@"http"]) {
            [self downloadHTML:request];
        }
    } else if (self.htmlString) {
        NSURL *url1 = [[NSBundle mainBundle] URLForResource:_htmlString withExtension:@"html"];
        [self.webView loadRequest:[NSURLRequest requestWithURL: url1]];
    }
}






- (void)downloadHTML:(NSMutableURLRequest *)request {
    
    [self.webView loadRequest:request];
}

- (void)clearData {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_webView.configuration.userContentController removeAllUserScripts];
    [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [_webView removeObserver:self forKeyPath:@"title"];
    [self.webView setNavigationDelegate:nil];
    [self.webView setUIDelegate:nil];
    _webView = nil;
}

- (void)addProgressBarForWebView {
    self.progress = [[UIProgressView alloc]initWithFrame:CGRectMake(0, self.webView.frame.origin.y, CGRectGetWidth(self.view.frame), 2)];
    self.progress.progressTintColor = UIColorHex(50D5D8);
    self.progress.trackTintColor = UIColorHex(eeeeee);
    [self.view addSubview:self.progress];
    // 给webview添加监听
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
}

//兼容一下 链接中含有中文
- (NSURL *)cz_URLWithString:(NSString *)stringURL {
    if (stringURL.length == 0) {
        return nil;
    }
    NSURL *url = [NSURL URLWithString:stringURL];
    if (!url) {
        NSString *tmpStringURL = [stringURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        url = [NSURL URLWithString:tmpStringURL];
    }
    return url;
}

/// WKWebView与原生交互方法
/// WKWebView可以使用prompt方法调用原生方法，并获得返回值。返回值为NSString类型。
/// prompt的格式为sldl://functionName
/// var info = window.prompt(text,defaultText);
/// @param prompt 方法
/// @param defaultText 参数
/// @param completionHandler 回调
- (void)bridgeJavaScriptWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText  completionHandler:(void (^)(NSString * _Nullable))completionHandler {
    NSString *funcName = [prompt componentsSeparatedByString:@"://"].lastObject;
    SEL funcSel = NSSelectorFromString(funcName);
    if ([self respondsToSelector:funcSel]) {
        NSMethodSignature *signature = [(SLWebViewController *)self methodSignatureForSelector:funcSel];
        if (signature == nil) {
            completionHandler(nil);
            return;
        }
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
        invocation.target = self;
        invocation.selector = funcSel;
        if ([funcName hasSuffix:@":"] && defaultText) {
            [invocation setArgument:&defaultText atIndex:2];
        }
        [invocation invoke];
        id __unsafe_unretained returnValue = nil;
        if (signature.methodReturnLength) {
           [invocation getReturnValue:&returnValue];
        }
        id value = returnValue;
        if (value && [value isKindOfClass:[NSString class]]) {
            completionHandler((NSString *)value);
        }else {
            completionHandler(nil);
        }
    }else {
        completionHandler(nil);
    }
}



#pragma mark - Observer

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey, id> *)change context:(void *)context {
    if ([keyPath isEqual:@"estimatedProgress"] && object == self.webView) {
        [self.progress setAlpha:1.0f];
        [self.progress setProgress:self.webView.estimatedProgress animated:YES];
        if (self.webView.estimatedProgress  >= 1.0f) {
            [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progress setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progress setProgress:0.0f animated:YES];
            }];
        }
    } else if ([keyPath isEqualToString:@"title"]) {
        if (object == self.webView) {
            if (_custemTitle.length > 0) {
                self.title = _custemTitle;
            } else {
                self.title = self.webView.title;
            }
        } else {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    } else {
//        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - WKNavigationDelegate
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    if (self.url.length > 0) {
     
 
        

    }
    
}

// 2 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    RTLog(@"页面开始加载时调用");
}

// 4 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    RTLog(@"当内容开始返回时调用");
}


// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation {
    RTLog(@"页面加载失败时调用");
}

// 接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
    RTLog(@"接收到服务器跳转请求之后调用");
}

// 3 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    RTLog(@"在收到响应后，决定是否跳转");

    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationResponsePolicyCancel);
}

// 1 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {

 
    NSString *absoluteStr = navigationAction.request.URL.absoluteString;
    __weak typeof(self) wself = self;
    RTLog(@"absoluteStr - %@",absoluteStr);
//    BOOL isYES = [SLPlusPayWebView payInterceptorWithUrl:absoluteStr block:^(NSDictionary *resultDic) {//这里是支付宝跳转类型
//        NSLog(@"%@", absoluteStr);
//        if ([webView canGoBack]) {
//            if ([resultDic[@"isProcessUrlPay"] boolValue]) {
//                // returnUrl 代表 第三方App需要跳转的成功页URL
//                NSString *urlStr = resultDic[@"returnUrl"];
//                if (urlStr.length > 0) {
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                                       NSURLRequest *webRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30];
//                                       [wself.webView loadRequest:webRequest];
//                                   });
//                }
//            }
//        }
//    }];
//    if (isYES) {
//        decisionHandler(WKNavigationActionPolicyCancel);//不允许跳转
//        return;
//    }

    if ([absoluteStr hasPrefix:@"boxmall"]) {
        decisionHandler(WKNavigationActionPolicyCancel);//不允许跳转
        [self shouldStartLoadWithUrl:absoluteStr];
    } else if ([absoluteStr hasPrefix:@"tel"]) {
        NSURL *URL = navigationAction.request.URL;
        NSString *resourceSpecifier = [URL resourceSpecifier];
        NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", resourceSpecifier];
        /// 防止iOS 10及其之后，拨打电话系统弹出框延迟出现
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone] options:@{} completionHandler:nil];
        decisionHandler(WKNavigationActionPolicyCancel);//不允许跳转
    } else if (self.htmlString && self.htmlString.length > 0) {//这个是空页面，加载个人中心通知时会显示。即加载htmlString
        decisionHandler(WKNavigationActionPolicyAllow);//允许跳转
    } else if (![absoluteStr hasPrefix:@"http"] && ![absoluteStr containsString:@".html"]) {//不是http,boxmall, tel,统一调用这个方法
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:absoluteStr] options:@{} completionHandler:nil];
        decisionHandler(WKNavigationActionPolicyCancel);//不允许跳转
    } else {
        decisionHandler(WKNavigationActionPolicyAllow);//允许跳转
    }
}

- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *_Nullable))completionHandler  {
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        if ([challenge previousFailureCount] == 0) {
            NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
            completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
        } else {
            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
        }
    } else {
        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
    }
}

- (BOOL)shouldStartLoadWithUrl:(NSString *)url {
    return YES;
}

#pragma mark - WKUIDelegate
// 创建一个新的WebView
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
    WKFrameInfo *frameInfo = navigationAction.targetFrame;
    if (![frameInfo isMainFrame]) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}

// 输入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *__nullable result))completionHandler {
    if ([prompt hasPrefix:@"sldl://"]) {
        [self bridgeJavaScriptWithPrompt:prompt defaultText:defaultText completionHandler:completionHandler];
    }else {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:nil preferredStyle:UIAlertControllerStyleAlert];
        // 输入框
        [alertController addTextFieldWithConfigurationHandler:^(UITextField *_Nonnull textField) {
            textField.placeholder = defaultText;
        }];
        // 确定按钮
        [alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
            // 返回用户输入的信息
            UITextField *textField = alertController.textFields.firstObject;
            completionHandler(textField.text);
        }]];
        // 显示
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

// 确认框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler {
    UIAlertAction *alertActionCancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
        // 返回用户选择的信息
        completionHandler(NO);
    }];
    UIAlertAction *alertActionOK = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
        completionHandler(YES);
    }];
    // alert弹出框
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:alertActionCancel];
    [alertController addAction:alertActionOK];
    [self presentViewController:alertController animated:YES completion:nil];
}

// 警告框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    if (CurrentVC == self) {
        // 确定按钮
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
            completionHandler();
        }];
        // alert弹出框
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:alertAction];
        [self presentViewController:alertController animated:YES completion:nil];
    } else {
        completionHandler();
    }
}




@end
